/**
 * @Description: 优惠券
 * @author ourslookAdmin
 * @date 2019-05-10 11:09:45
 */
import React, { Fragment } from 'react';
import Modal from 'drag-modal';
import moment from 'moment';
import numeral from 'numeral';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  BackTop,
  Avatar,
  Icon,
  Tooltip,
  Table,
  DatePicker,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import Ellipsis from '../../../components/ourslook/Ellipsis';

//import coming from '@/decorator/coming';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

//@coming({ title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2 })
@connect(() => ({}))
class MailCoupon extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '优惠券名称',
      dataIndex: 'title',
      align: 'center',
      sorter: false,
      key: 'title',
    },
    {
      title: '优惠券类型',
      dataIndex: 'appointType',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'appoint_type',
      render: (value, record, index) => {
        let appointTypeName = '';
        if (value === 1) {
          appointTypeName = `满减券`;
        } else if (value === 2) {
          appointTypeName = `折扣券`;
        } else {
          appointTypeName = `随机金额券`;
        }
        return appointTypeName;
      },
    },
    {
      title: '发放总量',
      dataIndex: 'stockQty',
      width: 80,
      align: 'center',
      sorter: false,
      key: 'stock_qty',
    },
    {
      title: '已领取',
      dataIndex: 'totalTake',
      width: 70,
      align: 'center',
      sorter: false,
      key: 'total_take',
      render: (value, record, index) => (
        <a
          onClick={() => {
            this.showUseTable(0, record.id);
          }}
        >
          {value}
        </a>
      ),
    },
    {
      title: '已使用',
      dataIndex: 'totalUsed',
      width: 70,
      align: 'center',
      sorter: false,
      key: 'total_used',
      render: (value, record, index) => (
        <a
          onClick={() => {
            this.showUseTable(1, record.id);
          }}
        >
          {value}
        </a>
      ),
    },
    {
      title: '使用门槛',
      dataIndex: 'condition',
      align: 'right',
      sorter: false,
      key: 'condition',
      width: 120,
      render: (value, record, index) => {
        let formatCondition = '-';
        if (value !== null && value !== undefined) {
          formatCondition = `￥${numeral(value).format('0,0.00')}`;
        }
        return formatCondition;
      },
    },
    {
      title: '面额',
      dataIndex: 'denominations',
      align: 'right',
      sorter: false,
      key: 'denominations',
      width: 120,
      render: (value, record, index) => {
        let formatCondition = '-';
        if (value !== null && value !== undefined) {
          if (record.appointType !== 2) {
            formatCondition = `￥${numeral(value).format('0,0.00')}`;
          } else {
            formatCondition = `${value}折`;
          }
        }
        return formatCondition;
      },
    },
    {
      title: '使用时间',
      dataIndex: 'validEndTime',
      align: 'center',
      sorter: false,
      key: 'validEndTime',
      width: 250,
      render: (value, record, index) => {
        let formatCondition = '';
        if (value !== null && value !== undefined) {
          formatCondition = `${record.validStartTime}至${record.validEndTime}`;
        }
        return formatCondition;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'status',
      fixed: 'right',
      render: (value, record, index) => {
        let statusName = '';
        if (value === 1) {
          statusName = '正常';
        } else if (value === 0) {
          statusName = '停止发券';
        } else if (value === 3) {
          statusName = '删除';
        }
        return statusName;
      },
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('mailcoupon:update') || record.status !== 1}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('mailcoupon:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('mailcoupon:info') || record.status !== 1}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.endCoupon();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.stop" defaultMessage="停止" />}>
              <Icon type="stop" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: MailCoupon.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      galleryModelVisible: false,
      confirmLoading: false,
      userDatas: [],
      userColumns: [
        {
          title: '用户id',
          dataIndex: 'userId',
          key: 'userId',
        },
        {
          title: '用户名称',
          dataIndex: 'username',
          key: 'username',
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          key: 'mobile',
        },
      ],
      userIds: [],
      userTable: [],
      userCols: [
        {
          title: '用户名/手机号',
          dataIndex: 'nameOrMobile',
          key: 'nameOrMobile',
          render: (value, record, index) => `${record.username}/${record.mobile}`,
        },
        {
          title: '领取日期/使用日期',
          dataIndex: 'time',
          key: 'time',
          render: (value, record, index) => {
            if (record.usedStatus === 0) {
              return record.createTime;
            }
            if (record.usedStatus === 1) {
              return record.usedTime;
            }
            return '';
          },
        },
      ],
      userModelVisible: false,
      usernameOrmobile: null
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'title',
      label: '优惠券名称',
      placeholder: '优惠券名称',
    },
    {
      type: 'SELECT',
      field: 'appointType',
      label: '优惠券类型',
      placeholder: '优惠券类型',
      list: [{ id: '', name: '请选择优惠券类型' }],
    },
    {
      type: 'SELECT',
      field: 'status',
      label: '状态',
      placeholder: '状态',
      list: [{ id: '', name: '请选择状态' }],
    },
  ];

  componentDidMount() {
    this.requestList();
    this.getAppointTypeList();
    this.getStatus();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  endCoupon = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }

    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(
      formatMessage({
        id:
          '停止发券后，买家之前领取的优惠券，在可用时间内还能继续使用，但无法再编辑优惠券内容。确定停止发券？',
      }),
      () => {
        this.setState({
          loading: true,
        });
        requestPromise(
          `${getWebPath()}mailcoupon/operateMailCouponByIds?modelIds=${ids}&status=0`,
          {
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded',
          }
        ).then(res => {
          this.setState({
            loading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              list: [],
            });
            this.requestList();
          }
        });
      }
    );
  };

  getUser = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    if (selectedRows[0].status !== 1) {
      uiUtils.showAlert('非正常状态的优惠券不能推送给用户！');
      return;
    }
    if (selectedRows[0].totalTake >= selectedRows[0].stockQty) {
      uiUtils.showAlert('优惠券已经被领取完毕，不能推送给用户！');
      return;
    }
    this.requestUserList(selectedRows[0].id);
    this.setState({
      galleryModelVisible: true,
      userSelectedIndexs: [],
      userSelectedRows: [],
      userSelectedIds: [],
    });
  };

  pushUser = productId => {
    if (this.state.userIds === undefined) {
      uiUtils.showAlert('请先选择用户');
      return;
    }
    this.setState({
      confirmLoading: true,
    });
    const data = {
      id: this.state.selectedIds[0],
      userIds: this.state.userSelectedIds,
    };
    requestPromise(`${getWebPath()}mailcoupon/pushCouponForUser`, {
      method: 'POST',
      body: data,
    }).then(res => {
      this.setState({
        confirmLoading: false,
        galleryModelVisible: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.requestList();
      }
    });
  };

  requestUserList = id => {
    //请求之前清空用户数据
    this.setState({
      userDatas: [],
      userLoading: true,
    });

    const params = {
      couponId: id,
    };
    requestPromise(`${getWebPath('/user/list')}`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: params,
    }).then(res => {
      this.setState({
        userLoading: false,
      });
      if (res && res.code === 0) {
        const userDatas = res.page.list || [];
        this.setState({
          userDatas,
        });
      }
    });
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        appointType: 1,
        conditionType: 0,
        onlineRangeType: 'all',
        userLevel: 1,
        isLimitType: 1,
        isLimit: 1,
        dateType: 1,
        isShare: true,
        expireNotice: false,
        isSyncWeixin: true,
        isForbidPreference: false,
      },
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  showUseTable = (usedStatus, couponId) => {
    this.setState({
      userModelVisible: true,
      userTable: [],
    });
    const data = {
      usedStatus,
      couponId,
    };
    requestPromise(`${getWebPath()}mailcoupon/queryCouponUserByStatus`, {
      method: 'POST',
      body: data,
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          userTable: res.mailCouponUsedVoList,
        });
      }
    });
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}mailcoupon/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const mailCoupon = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = mailCoupon.id == null ? '/mailcoupon/save' : '/mailcoupon/update';

        //校验数据是否必填
        if (
          mailCoupon.conditionType === 1 &&
          (mailCoupon.condition === undefined || mailCoupon.condition === '')
        ) {
          uiUtils.showAlert('使用门槛不能为空！', 'error');
          return;
        }
        if (
          mailCoupon.dateType === 1 &&
          (mailCoupon.validStartTime === null || mailCoupon.validEndTime === null)
        ) {
          uiUtils.showAlert('用券时间不能为空！', 'error');
          return;
        }
        if (
          (mailCoupon.dateType === 2 &&
            (mailCoupon.validDayNow === undefined || mailCoupon.validDayNow === '')) ||
          (mailCoupon.dateType === 3 &&
            (mailCoupon.validDaySecond === undefined || mailCoupon.validDaySecond === ''))
        ) {
          uiUtils.showAlert('用券时间不能为空！', 'error');
          return;
        }
        if (
          mailCoupon.isLimitType === 1 &&
          (mailCoupon.isLimit === undefined || mailCoupon.isLimit === '')
        ) {
          uiUtils.showAlert('每人限领次数不能为空！', 'error');
          return;
        }
        if (
          mailCoupon.expireNotice === true &&
          (mailCoupon.expireNoticeDays === undefined || mailCoupon.expireNoticeDays === '')
        ) {
          uiUtils.showAlert('过期提醒天数不能为空！', 'error');
          return;
        }
        //对象的mailCouponRangeList字段赋值
        if (mailCoupon.onlineRangeType === 'part') {
          const { partMailCouponRanges: newPartMailCouponRanges } = this.editForm.state;
          if (this.editForm.state.deletePartIds.length > 0) {
            for (let i = 0; i < this.editForm.state.deletePartIds.length; i += 1) {
              newPartMailCouponRanges.push({
                id: this.editForm.state.deletePartIds[i],
                status: '3',
              });
            }
          }
          mailCoupon.mailCouponRangeList = newPartMailCouponRanges;
        } else if (mailCoupon.onlineRangeType === 'excluded') {
          const { excludedMailCouponRanges: newExcludedMailCouponRanges } = this.editForm.state;
          if (this.editForm.state.deleteExcludedIds.length > 0) {
            for (let i = 0; i < this.editForm.state.deleteExcludedIds.length; i += 1) {
              newExcludedMailCouponRanges.push({
                id: this.editForm.state.deleteExcludedIds[i],
                status: '3',
              });
            }
          }
          mailCoupon.mailCouponRangeList = newExcludedMailCouponRanges;
        }
        //用券时间
        if (mailCoupon.dateType === 1) {
          mailCoupon.validStartTime = `${mailCoupon.validStartTime.format('YYYY-MM-DD HH:mm:ss')}`;
          mailCoupon.validEndTime = `${mailCoupon.validEndTime.format('YYYY-MM-DD HH:mm:ss')}`;
        } else {
          mailCoupon.validStartTime = undefined;
          mailCoupon.validEndTime = undefined;
        }
        //用券天数
        if (mailCoupon.dateType === 2) {
          mailCoupon.validDays = mailCoupon.validDayNow;
        } else if (mailCoupon.dateType === 3) {
          mailCoupon.validDays = mailCoupon.validDaySecond;
        }
        mailCoupon.isLimit = mailCoupon.isLimitType === 0 ? 0 : mailCoupon.isLimit;
        mailCoupon.expireNotice = mailCoupon.expireNotice === true ? 1 : 0;
        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: mailCoupon,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!mailCoupon.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = (id, type) => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(`${getWebPath(`/mailcoupon/infoVo/${id}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });

      if (res && res.code === 0) {
        const mailCouponVo = res.mailCouponVo;

        mailCouponVo.conditionType = mailCouponVo.condition === undefined ? 0 : 1;
        mailCouponVo.isLimitType = mailCouponVo.isLimit === 0 ? 0 : 1;

        if (mailCouponVo.expireNotice === 1) {
          mailCouponVo.expireNotice = true;
        } else {
          mailCouponVo.expireNotice = false;
        }

        if (mailCouponVo.dateType === 2) {
          mailCouponVo.validDayNow = mailCouponVo.validDays;
        } else if (mailCouponVo.dateType === 3) {
          mailCouponVo.validDaySecond = mailCouponVo.validDays;
        }

        this.editForm.setState({
          couponDetail: {
            title: mailCouponVo.title,
            denominations: mailCouponVo.denominations,
            condition: mailCouponVo.condition,
            description: mailCouponVo.description,
          },
        });

        this.setState({
          editModel: mailCouponVo,
        });
        if (mailCouponVo.onlineRangeType === 'part') {
          this.editForm.setState({
            selectPartProductIds:mailCouponVo.productIds,
            partMailCouponRanges: mailCouponVo.mailCouponRangeList,
          });
        } else if (mailCouponVo.onlineRangeType === 'excluded') {
          this.editForm.setState({
            selectExcludedProductIds:mailCouponVo.productIds,
            excludedMailCouponRanges: mailCouponVo.mailCouponRangeList,
          });
        }
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}mailcoupon/list`, this.params);
  };

  queryTable = () => {
    this.setState({
      userDatas: [],
      userLoading: true,
    });

    const params = {
      couponId: this.state.selectedIds[0],
      usernameOrmobile:this.state.usernameOrmobile
    };
    requestPromise(`${getWebPath('/user/list')}`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: params,
    }).then(res => {
      this.setState({
        userLoading: false,
      });
      if (res && res.code === 0) {
        const userDatas = res.page.list || [];
        this.setState({
          userDatas,
        });
      }
    });
  };

  getAppointTypeList = () => {
    const newAppointType = [
      { id: '', name: '请选择优惠券类型' },
      { id: 1, name: '满减券' },
      { id: 2, name: '折扣券' },
      { id: 3, name: '随机金额券' },
    ];
    const formItem = this.findFormListItemByField('appointType');
    formItem.list = newAppointType;
  };

  getStatus = () => {
    const newSatus = [
      { id: '', name: '请选择状态' },
      { id: '1', name: '正常' },
      { id: '0', name: '停止发券' },
      { id: '3', name: '删除' },
    ];
    const formItem = this.findFormListItemByField('status');
    formItem.list = newSatus;
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const colSpanLayout = { md: 10, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('mailcoupon:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('mailcoupon:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
            <Button type="default" icon="info-circle" {...style} onClick={this.getUser}>
              <FormattedMessage id="ours.curd.list.pushUser" defaultMessage="推送至用户" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1370 }}
            />
          </div>
        </Card>

        <BackTop />

        <Modal
          width={700}
          height={500}
          visible={this.state.userModelVisible}
          title="用户"
          onCancel={() => {
            this.setState({
              userModelVisible: false,
            });
          }}
        >
          <Table columns={this.state.userCols} dataSource={this.state.userTable} />
        </Modal>

        <Modal
          width={700}
          height={500}
          destroyOnClose
          visible={this.state.galleryModelVisible}
          title="推送至用户"
          onCancel={() => {
            this.setState({
              galleryModelVisible: false,
            });
          }}
          onOk={this.pushUser}
          confirmLoading={this.state.confirmLoading}
          saveDistance={0}
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="用户名称/手机号"
                onChange={e => {
                  this.setState({
                    usernameOrmobile: e.target.value
                  });
                }}
                onPressEnter={this.queryTable}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button
                type="primary"
                icon="search"
                onClick={this.queryTable}
              >
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <ETable
            onSelectRow={uiUtils.onSelectRow.bind(this)}
            onSelectRowKeys={['userSelectedIndexs', 'userSelectedRows', 'userSelectedIds']}
            primaryKey="userId"
            selectedIndexs={this.state.userSelectedIndexs}
            selectedRows={this.state.userSelectedRows}
            selectedIds={this.state.userSelectedIds}
            columns={this.state.userColumns}
            dataSource={this.state.userDatas}
            loading={this.state.userLoading}
            allowMultiPageSelects
          />
        </Modal>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default MailCoupon;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  params = {
    page: 1,
    limit: 10,
  };

  constructor(props) {
    super(props);
    this.state = {
      couponDetail: {
        title: '',
        denominations: '',
        condition: '',
        description: '',
      },
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      willSelectProductVisible: false,
      willSelectProductColumns: [
        {
          title: '商品名称',
          dataIndex: 'productName',
          key: 'productName',
          render: value => (
            <Ellipsis length={60} tooltip>
              {value}
            </Ellipsis>
          ),
        },
      ],
      partMailCouponColumns: [
        {
          title: '商品名称',
          dataIndex: 'productName',
          key: 'productName',
          render: value => (
            <Ellipsis length={50} tooltip>
              {value}
            </Ellipsis>
          ),
        },
        {
          title: '操作',
          key: '',
          dataIndex: '',
          width: 50,
          fixed: 'right',
          render: (value, record, index) => (
            <React.Fragment>
              <a
                hidden={this.props.type === 'view'}
                onClick={() => {
                  this.deleteProduct(record, index);
                }}
              >
                <Tooltip
                  title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
                >
                  <Icon type="delete" />
                </Tooltip>
              </a>
            </React.Fragment>
          ),
        },
      ],
      partMailCouponRanges: [],
      excludedMailCouponRanges: [],
      limitList: [
        { id: 1, name: 1 },
        { id: 2, name: 2 },
        { id: 3, name: 3 },
        { id: 4, name: 4 },
        { id: 5, name: 5 },
        { id: 10, name: 10 },
      ],
      expireNoticeDaysList: this.getExpireNoticeDaysList(),
      deletePartIds: [],
      deleteExcludedIds: [],
      selectPartProductIds: '',
      selectExcludedProductIds: '',
      likeProductName:null
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getExpireNoticeDaysList = () => {
    const expireNoticeDaysList = [];
    for (let i = 1; i < 15; i += 1) {
      expireNoticeDaysList.push({ id: i, name: i });
    }
    return expireNoticeDaysList;
  };

  deleteProduct = (record, index) => {
    const {
      partMailCouponRanges: newPartMailCouponRanges,
      excludedMailCouponRanges: newExcludedMailCouponRanges,
      deletePartIds: newDeletePartIds,
      deleteExcludedIds: newDeleteExcludedIds,
    } = this.state;
    if (this.props.model.onlineRangeType === 'part') {
      if (record.id !== null && record.id !== undefined) {
        newDeletePartIds.push(record.id);
      }
      newPartMailCouponRanges.splice(index, 1);
      this.setState({
        partMailCouponRanges: newPartMailCouponRanges,
        deletePartIds: newDeletePartIds,
      });
    } else if (this.props.model.onlineRangeType === 'excluded') {
      if (record.id !== null && record.id !== undefined) {
        newDeleteExcludedIds.push(record.id);
      }
      newExcludedMailCouponRanges.splice(index, 1);
      this.setState({
        excludedMailCouponRanges: newExcludedMailCouponRanges,
        deleteExcludedIds: newDeleteExcludedIds,
      });
    }
  };

  selectProduct = () => {
    const { selectedRows } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }

    if (this.props.model.onlineRangeType === 'part') {
      for (let i = 0; i < selectedRows.length; i += 1) {
        this.state.selectPartProductIds += `${selectedRows[i].id},`;
      }

      const { partMailCouponRanges: newPartMailCouponRanges } = this.state;
      for (let i = 0; i < selectedRows.length; i += 1) {
        const item = {
          id: null,
          productId: selectedRows[i].id,
          productName: selectedRows[i].productName,
          couponId: null,
        };
        newPartMailCouponRanges.push(item);
      }
      this.setState({
        partMailCouponRanges: newPartMailCouponRanges,
        willSelectProductVisible: false,
      });
    } else if (this.props.model.onlineRangeType === 'excluded') {
      for (let i = 0; i < selectedRows.length; i += 1) {
        this.state.selectExcludedProductIds += `${selectedRows[i].id},`;
      }

      const { excludedMailCouponRanges: newExcludedMailCouponRanges } = this.state;
      for (let i = 0; i < selectedRows.length; i += 1) {
        const item = {
          id: null,
          productId: selectedRows[i].id,
          productName: selectedRows[i].productName,
          couponId: null,
        };
        newExcludedMailCouponRanges.push(item);
      }
      this.setState({
        excludedMailCouponRanges: newExcludedMailCouponRanges,
        willSelectProductVisible: false,
      });
    }
  };

  willSelectProduct = () => {
    this.setState({
      willSelectProductVisible: true,
    });
    this.params.page = 1;
    this.state.likeProductName = null;
    if (this.props.model.onlineRangeType === 'part') {
      this.params.notInProductIds = this.state.selectPartProductIds;
    } else if (this.props.model.onlineRangeType === 'excluded') {
      this.params.notInProductIds = this.state.selectExcludedProductIds;
    }
    this.requestList();
  };

  requestList = () => {
    this.params.productName = this.state.likeProductName;
    this.params.status = 2;
    requestLists(this, `${getWebPath()}mailproduct/listByNotInProductIds`, this.params);
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const colFirstSpanLayout = { md: 10, sm: 24 };
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const gridTextStyle = {
      float: 'right',
      fontSize: '14px',
      display: 'inline-block',
      whitespace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
    };
    const gridUserStyle = {
      width: '100%',
      padding: '10px',
      paddingLeft: '30px',
      paddingRight: '30px',
      textAlign: 'left',
    };
    const pStyle = {
      fontWeight: '700',
      fontSize: '16px',
      color: '#333',
      marginBottom: '20px',
    };
    const checkStockQtyData = (rule, value, callback) => {
      if (value && type === 'update') {
        if (value < model.stockQty) {
          callback(new Error('发放总量只能增加不能减少'));
        }
      }
      callback();
    };
    const checkDenominationsData = (rule, value, callback) => {
      if (value && model.appointType === 2) {
        if (value > 10 || value < 1) {
          callback(new Error('折扣价只能在1-10之间'));
        }
      }
      callback();
    };

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col
            {...colFirstSpanLayout}
            style={{
              width: '320px',
              background: '#fafafa',
              marginRight: '30px',
              height: '568px',
              paddingLeft: '0px',
              paddingRight: '0px',
            }}
          >
            <Card
              bordered
              hoverable
              size="small"
              bodyStyle={{ padding: 0, margin: 0 }}
              style={{ marginBottom: 0 }}
              title="优惠券信息"
            />
            <Card.Grid style={{ width: '100%', padding: '0', margin: '0' }}>
              <div
                style={{
                  paddingTop: '20px',
                  backgroundColor: '#1890ff',
                  height: '158px',
                  color: 'white',
                  overflow: 'hidden',
                }}
              >
                <div
                  style={{
                    textAlign: 'center',
                    height: '60px',
                    display: 'flex',
                    alignItems: 'center',
                    boxSizing: 'border-box',
                    padding: '0px 10px',
                    lineHeight: '60px',
                    maxWidth: '290px',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                    fontSize: '18px',
                  }}
                >
                  {this.state.couponDetail.title}
                </div>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    textAlign: 'center',
                    alignItems: 'center',
                  }}
                >
                  <div
                    style={{
                      fontSize: '30px',
                      lineHeight: '40px',
                      maxWdth: '80%',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      height: '40px',
                      overflow: 'hidden',
                    }}
                  >
                    {(model.appointType === 1 || model.appointType === 3) &&
                      this.state.couponDetail.denominations !== '' &&
                      this.state.couponDetail.denominations !== undefined &&
                      `减免${this.state.couponDetail.denominations}元`}
                    {model.appointType === 2 &&
                      this.state.couponDetail.denominations !== '' &&
                      this.state.couponDetail.denominations !== undefined &&
                      `${this.state.couponDetail.denominations}折`}
                  </div>
                  <p
                    style={{
                      lineHeight: '1.5',
                      maxWdth: 'calc(100% - 20px)',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      padding: '10px 0px',
                      overflow: 'hidden',
                    }}
                  >
                    {this.state.couponDetail.condition !== '' &&
                      this.state.couponDetail.condition !== undefined &&
                      `满${this.state.couponDetail.condition}元`}
                    {this.state.couponDetail.condition === '' && `无限制`}
                  </p>
                </div>
              </div>
              <p>使用说明</p>
              <Card.Grid style={gridUserStyle}>
                <p>{this.state.couponDetail.description}</p>
              </Card.Grid>
            </Card.Grid>
          </Col>
          <Col {...colSpanLayout}>
            <p style={pStyle}>基本信息</p>
            <Col>
              <FormItem label="优惠券名称" {...formItemLayout}>
                {getFieldDecorator('title', {
                  initialValue: model.title,
                  rules: [
                    {
                      required: true,
                      message: '优惠券名称必填',
                    },
                    {
                      max: 32,
                      message: '最长32个字符',
                    },
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="优惠券名称"
                    disabled={type !== 'add'}
                    onBlur={e => {
                      const { couponDetail: newcouponDetail } = this.state;
                      newcouponDetail.title = e.target.value;
                      this.setState({
                        couponDetail: newcouponDetail,
                      });
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="优惠券类型" {...formItemLayout}>
                {getFieldDecorator('appointType', {
                  initialValue: model.appointType,
                })(
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择优惠券类型"
                    onChange={value => {
                      model.appointType = value;
                    }}
                    disabled={type !== 'add'}
                  >
                    <option value={1}>满减券</option>
                    <option value={2}>折扣券</option>
                    {/*<option value={3}>随机金额券</option>*/}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="发放总量" {...formItemLayout}>
                {getFieldDecorator('stockQty', {
                  initialValue: model.stockQty,
                  rules: [
                    {
                      required: true,
                      message: '发放总量必填',
                    },
                    {
                      validator: checkStockQtyData,
                      trigger: 'blur',
                    },
                    rulesReg('plus'),
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="发放总量"
                    addonAfter="张"
                    disabled={type === 'view'}
                    style={{ width: '90%' }}
                  />
                )}
                &nbsp;&nbsp;
                <Tooltip placement="right" title="修改优惠券总量时只能增加不能减少，请谨慎设置">
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col>
              <FormItem label="适用商品" {...formItemLayout}>
                {getFieldDecorator('onlineRangeType', {
                  initialValue: model.onlineRangeType,
                })(
                  <RadioGroup
                    onChange={e => {
                      model.onlineRangeType = e.target.value;
                    }}
                    disabled={type === 'view'}
                  >
                    <Radio value="all">全部商品可用</Radio>
                    <br />
                    <Radio value="part">
                      指定商品可用
                      <br />
                      {model.onlineRangeType === 'part' && (
                        <div>
                          {type !== 'view' && (
                            <a
                              onClick={() => {
                                this.willSelectProduct();
                              }}
                            >
                              选择商品
                            </a>
                          )}
                          {this.state.partMailCouponRanges.length > 0 && (
                            <Table
                              style={{ minWidth: '450px' }}
                              columns={this.state.partMailCouponColumns}
                              dataSource={this.state.partMailCouponRanges}
                            />
                          )}
                        </div>
                      )}
                    </Radio>
                    <br />
                    <Radio value="excluded">指定商品不可用</Radio>
                    <br />
                    {model.onlineRangeType === 'excluded' && (
                      <div>
                        {type !== 'view' && (
                          <a
                            onClick={() => {
                              this.willSelectProduct();
                            }}
                          >
                            选择商品
                          </a>
                        )}
                        {this.state.excludedMailCouponRanges.length > 0 && (
                          <Table
                            style={{ minWidth: '450px' }}
                            columns={this.state.partMailCouponColumns}
                            dataSource={this.state.excludedMailCouponRanges}
                          />
                        )}
                      </div>
                    )}
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="使用门槛" {...formItemLayout}>
                {getFieldDecorator('conditionType', {
                  initialValue: model.conditionType,
                })(
                  <RadioGroup
                    onChange={e => {
                      model.conditionType = e.target.value;
                    }}
                    disabled={type !== 'add'}
                  >
                    <Radio value={0}>无使用门槛</Radio>
                    <br />
                    <Radio value={1}>
                      订单满：
                      {getFieldDecorator('condition', {
                        initialValue: model.condition,
                      })(
                        <Input
                          type="text"
                          autocomplete="off"
                          disabled={model.conditionType === 0 || type !== 'add'}
                          onBlur={e => {
                            const { couponDetail: newcouponDetail } = this.state;
                            newcouponDetail.condition = e.target.value;
                            this.setState({
                              couponDetail: newcouponDetail,
                            });
                          }}
                        />
                      )}
                      元
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="优惠内容" {...formItemLayout}>
                {getFieldDecorator('denominations', {
                  initialValue: model.denominations,
                  rules: [
                    {
                      required: true,
                      message: '优惠内容必填',
                    },
                    {
                      validator: checkDenominationsData,
                      trigger: 'blur',
                    },
                    rulesReg('money_0_999999'),
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="优惠内容"
                    disabled={type !== 'add'}
                    addonAfter={model.appointType === 2 ? '折' : '元'}
                    onBlur={e => {
                      const { couponDetail: newcouponDetail } = this.state;
                      newcouponDetail.denominations = e.target.value;
                      this.setState({
                        couponDetail: newcouponDetail,
                      });
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="用券时间" {...formItemLayout}>
                {getFieldDecorator('dateType', {
                  initialValue: model.dateType,
                  rules: [
                    {
                      required: true,
                      message: '用券时间必填',
                    },
                  ],
                })(
                  <RadioGroup
                    onChange={e => {
                      model.dateType = e.target.value;
                    }}
                    disabled={type !== 'add'}
                  >
                    <Radio value={1}>
                      {getFieldDecorator('validStartTime', {
                        initialValue: moment(
                          model.validStartTime === undefined ? moment() : model.validStartTime,
                          'YYYY-MM-DD HH:mm:ss'
                        ),
                      })(
                        <DatePicker
                          disabled={type !== 'add'}
                          showTime
                          placeholder="开始时间"
                          defaultValue={moment(
                            model.validStartTime === undefined ? moment() : model.validStartTime,
                            'YYYY-MM-DD HH:mm:ss'
                          )}
                        />
                      )}
                      <span>至</span>
                      {getFieldDecorator('validEndTime', {
                        initialValue: moment(
                          model.validEndTime === undefined ? moment() : model.validEndTime,
                          'YYYY-MM-DD HH:mm:ss'
                        ),
                      })(
                        <DatePicker
                          disabled={type !== 'add'}
                          showTime
                          placeholder="结束时间"
                          defaultValue={moment(
                            model.validEndTime === undefined ? moment() : model.validEndTime,
                            'YYYY-MM-DD HH:mm:ss'
                          )}
                        />
                      )}
                    </Radio>
                    <br />
                    <Radio value={2}>
                      领券当日起：
                      {getFieldDecorator('validDayNow', {
                        initialValue: model.validDayNow,
                      })(
                        <Input
                          type="text"
                          autocomplete="off"
                          disabled={model.dateType !== 2 || type !== 'add'}
                          style={{ width: '60px' }}
                        />
                      )}
                      天内可用
                    </Radio>
                    <br />
                    <Radio value={3}>
                      领券次日起：
                      {getFieldDecorator('validDaySecond', {
                        initialValue: model.validDaySecond,
                      })(
                        <Input
                          type="text"
                          autocomplete="off"
                          disabled={model.dateType !== 3 || type !== 'add'}
                          style={{ width: '60px' }}
                        />
                      )}
                      天内可用
                    </Radio>
                    <br />
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <p style={pStyle}>领取和使用规则</p>
            <Col>
              <FormItem label="领取人限制" {...formItemLayout}>
                {getFieldDecorator('userLevel', {
                  initialValue: model.userLevel,
                })(
                  <RadioGroup
                    onChange={e => {
                      model.userLevel = e.target.value;
                    }}
                    disabled={type !== 'add'}
                  >
                    <Radio value={1}>不限制，所有人可领</Radio>
                    <br />
                    <Radio value={2}>指定会员等级可领</Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="每人限领次数" {...formItemLayout}>
                {getFieldDecorator('isLimitType', {
                  initialValue: model.isLimitType,
                })(
                  <RadioGroup
                    onChange={e => {
                      model.isLimitType = e.target.value;
                    }}
                    disabled
                  >
                    <Radio value={0}>不限次数</Radio>
                    <br />
                    <Radio value={1}>
                      {getFieldDecorator('isLimit', {
                        initialValue: model.isLimit,
                      })(
                        <Select
                          style={{ width: '100px' }}
                          placeholder="请选择"
                          onChange={value => {
                            model.isLimit = value;
                          }}
                          disabled
                        >
                          {uiUtils.getOptionList(this.state.limitList)}
                        </Select>
                      )}
                      次
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="分享设置" {...formItemLayout}>
                {getFieldDecorator('isShare', {
                  initialValue: model.isShare,
                })(
                  <Checkbox
                    checked={model.isShare}
                    onChange={e => {
                      model.isShare = e.target.checked;
                    }}
                    disabled={type === 'view'}
                  >
                    优惠券允许分享给好友领取
                  </Checkbox>
                )}
              </FormItem>
            </Col>
            <Col>
              <FormItem label="使用说明" {...formItemLayout}>
                {getFieldDecorator('description', {
                  initialValue: model.description,
                  rules: [
                    {
                      required: true,
                      message: '使用说明必填',
                    },
                  ],
                })(
                  <TextArea
                    type="text"
                    autocomplete="off"
                    placeholder="使用说明"
                    disabled={type === 'view'}
                    onBlur={e => {
                      const { couponDetail: newcouponDetail } = this.state;
                      newcouponDetail.description = e.target.value;
                      this.setState({
                        couponDetail: newcouponDetail,
                      });
                    }}
                  />
                )}
                {/*&nbsp;&nbsp;
                <Tooltip
                  placement="right"
                  title={
                    <div>
                      <p>庆国庆优惠券</p>
                      <div>使用时间：2017-10-27 12:00:00 - 2017-10-29 14:49:06</div>
                      <div>优惠内容：部分商品，满88元8.8折优惠券</div>
                      <div>其他限制：仅原价购买商品时可用券</div>
                    </div>
                  }
                >
                  <a>查看实例</a>
                </Tooltip>*/}
              </FormItem>
            </Col>
            <p style={pStyle}>更多设置</p>
            <Col>
              <FormItem label="过期提醒" {...formItemLayout}>
                {getFieldDecorator('expireNotice', {
                  initialValue: model.expireNotice,
                })(
                  <Checkbox
                    checked={model.expireNotice}
                    disabled={type === 'view'}
                    onChange={e => {
                      model.expireNotice = e.target.checked;
                    }}
                  >
                    优惠券过期前&nbsp;
                    {getFieldDecorator('expireNoticeDays', {
                      initialValue: model.expireNoticeDays,
                    })(
                      <Select
                        disabled={type === 'view' || model.expireNotice === false}
                        style={{ width: '100px' }}
                        placeholder="请选择"
                        onChange={value => {
                          model.expireNoticeDays = value;
                        }}
                      >
                        {uiUtils.getOptionList(this.state.expireNoticeDaysList)}
                      </Select>
                    )}
                    天提醒
                  </Checkbox>
                )}
                &nbsp;&nbsp;
                <Tooltip
                  placement="right"
                  title="建议设置的天数小于优惠券的有效期，否则用户无法收到过期提醒"
                >
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col>
              <FormItem label="使用限制" {...formItemLayout}>
                {getFieldDecorator('isForbidPreference', {
                  initialValue: model.isForbidPreference,
                })(
                  <Checkbox
                    onChange={e => {
                      model.isForbidPreference = e.target.checked;
                    }}
                    checked={model.isForbidPreference}
                    disabled={type !== 'view'}
                  >
                    优惠券仅原价购买商品时可用
                  </Checkbox>
                )}
                &nbsp;&nbsp;
                <Tooltip
                  placement="right"
                  title="勾选时，如果商品参与了其他营销活动，如限时折扣、团购等，则优惠券不可用"
                >
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
          </Col>
        </Row>
        <Modal
          width={700}
          height={500}
          visible={this.state.willSelectProductVisible}
          title="选择商品"
          onCancel={() => {
            this.setState({
              willSelectProductVisible: false,
            });
          }}
          onOk={this.selectProduct}
          destroyOnClose
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="商品名称"
                onChange={e => {
                  this.setState({
                    likeProductName: e.target.value
                  });
                }}
                onPressEnter={this.requestList}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button
                type="primary"
                icon="search"
                onClick={this.requestList}
              >
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <ETable
            onSelectRow={uiUtils.onSelectRow.bind(this)}
            primaryKey="id"
            selectedRows={this.state.selectedRows}
            selectedIds={this.state.selectedIds}
            selectedIndexs={this.state.selectedIndexs}
            columns={this.state.willSelectProductColumns}
            dataSource={this.state.list}
            pagination={this.state.pagination}
            loading={this.state.loading}
            scroll={{ x: 900 }}
          />
        </Modal>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
